package com.yanyq.week02.util;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Objects;
import java.util.logging.Logger;

/**
 * connection 管理
 */
public class DBConnManager {
    private static Logger logger = Logger.getLogger(DBConnManager.class.getName());
    //MySQL数据库配置的JNDI数据源连接名，java:comp/env是必须加的,后面跟的是DataSource名
    private static final String MYSQL_DB_JNDI_NAME = "java:comp/env/jdbc/MysqlDataSource";

    private static DataSource dataSource = null;

    static {
        try {
            logger.info("获取dataSource");
            // 初始化名称查找上下文
            Context context = new InitialContext();
            // 通过jndi名称找DataSource
            dataSource = (DataSource) context.lookup(MYSQL_DB_JNDI_NAME);
        } catch (NamingException e) {
            logger.info("获取dataSource失败");
            e.printStackTrace();
        }
    }

    /**
     * 获取connection
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 关闭
     * @param connection
     * @param statement
     * @param resultSet
     */
    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        if (!Objects.isNull(connection)) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (!Objects.isNull(statement)) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (!Objects.isNull(resultSet)) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}
